#include "drv_adc_init.h"

void DPM_AdcInit(void)
{
	// 启用外设时钟
	RCC_AHB_Peripheral_Clock_Enable(RCC_AHB_PERIPH_GPIOA | RCC_AHB_PERIPH_GPIOB | RCC_AHB_PERIPH_ADC);
	ADC_Clock_Mode_Config(ADC_CKMOD_AHB, RCC_ADCHCLK_DIV16);
	RCC_ADC_1M_Clock_Config(RCC_ADC1MCLK_SRC_HSI, RCC_ADC1MCLK_DIV8); // selsect HSE as RCC ADC1M CLK Source

    GPIO_InitType GPIO_InitStructure;
	// 将ADC相关引脚设置工作模式设置为模拟模式
    //电流电压检测引脚
	GPIO_Structure_Initialize(&GPIO_InitStructure);
	GPIO_InitStructure.Pin = GPIO_PIN_1 | GPIO_PIN_2;
	GPIO_InitStructure.GPIO_Mode = GPIO_MODE_ANALOG;
	GPIO_Peripheral_Initialize(GPIOA, &GPIO_InitStructure);
    //外部模拟信号引脚
    GPIO_Structure_Initialize(&GPIO_InitStructure);
	GPIO_InitStructure.Pin = GPIO_PIN_11;
	GPIO_InitStructure.GPIO_Mode = GPIO_MODE_ANALOG;
	GPIO_Peripheral_Initialize(GPIOB, &GPIO_InitStructure);

    ADC_InitType ADC_InitStructure;
	// 配置ADC参数
	ADC_InitStructure.MultiChEn = DISABLE;
	ADC_InitStructure.ContinueConvEn = DISABLE;
	ADC_InitStructure.ExtTrigSelect = ADC_EXT_TRIGCONV_REGULAR_SWSTRRCH;
	ADC_InitStructure.DatAlign = ADC_DAT_ALIGN_R;
	ADC_InitStructure.ChsNumber = ADC_REGULAR_LEN_1;
	ADC_Initializes(&ADC_InitStructure);

    // 启动ADC
	ADC_ON();
	// 等待ADC就绪
	while (ADC_Flag_Status_Get(ADC_RD_FLAG, ADC_FLAG_AWDG, ADC_FLAG_RDY) == RESET)
	{
		__NOP();
	}
	// 启动ADC自校准
	ADC_Calibration_Operation(ADC_CALIBRATION_ENABLE);
	// 等待ADC自校准完成
	while (ADC_Calibration_Operation(ADC_CALIBRATION_STS) == SET)
	{
		__NOP();
	}
}

uint16_t DPM_AdcGet(uint8_t ADC_Channel)
{
	// 配置采样参数
	ADC_Channel_Sample_Time_Config(ADC_Channel, ADC_SAMP_TIME_55CYCLES5);
	ADC_Regular_Sequence_Conversion_Number_Config(ADC_Channel, ADC_REGULAR_NUMBER_1);

	// 启动ADC转换
	ADC_Regular_Channels_Software_Conversion_Operation(ADC_EXTRTRIG_SWSTRRCH_ENABLE);
	// 等待ADC转换完成
	while (ADC_Flag_Status_Get(ADC_RUN_FLAG, ADC_FLAG_ENDC, ADC_FLAG_RDY) == 0)
	{
		__NOP();
	}
	ADC_Flag_Status_Clear(ADC_FLAG_ENDC);
	ADC_Flag_Status_Clear(ADC_FLAG_STR);
	
	// 获取ADC采样值
	return ADC_Regular_Group_Conversion_Data_Get();
}

double DPM_CurrentRead(void)
{
	uint32_t adc_current_get = 0;
	double current=0;
	for(int i = 0; i < 16; i++)
	{
		adc_current_get += DPM_AdcGet(CURRENT_ADC_CHANNEL);
	}
	adc_current_get >>= 4;
	current = adc_current_get * CURRENT_FACTOR /1000.0;  //单位A
	return current;
}

double DPM_InVoltageRead(void)
{
	uint32_t adc_in_voltage_get = 0;
	double in_voltage=0;
	for(int i = 0; i < 16; i++)
	{
		adc_in_voltage_get += DPM_AdcGet(VOLTAGE_ADC_CHANNEL);
	}
	adc_in_voltage_get >>= 4;
	in_voltage = adc_in_voltage_get * VOLTAGE_FACTOR /1000.0;  //单位V
	return in_voltage;
}

double DPM_ExVoltageRead(void)
{
	uint32_t adc_ex_voltage_get = 0;
	double ex_voltage=0;
	for(int i = 0; i < 16; i++)
	{
		adc_ex_voltage_get += DPM_AdcGet(EX_ADC_CHANNEL);
	}
	adc_ex_voltage_get >>= 4;
	ex_voltage = adc_ex_voltage_get * VOLTAGE_FACTOR /1000.0;  //单位V
	return ex_voltage;
}


